package com.igatewebsol.common;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;

public class QueryFactory {

	private static Configuration queryConfig;
	// This is a static class. Instances of this class will not be created.
	private QueryFactory() {}

	public static String getDBQuery(String queryName) {
		
		String dbQuery = null;
		
		// validate and clean input
		if (queryName == null || queryName.trim().equals(""))
			return null;
		else
			queryName = queryName.trim();

		// read the configuration file
		if (queryConfig == null)
			{
			try
				{
					queryConfig = new XMLConfiguration("queries.xml");
				}
			catch (Exception e)
				{
					e.printStackTrace();
					//throw new CMSException(e);
				}
			}
		if (queryConfig != null)
			{
			try
				{
				dbQuery = null;

				// loop through all the dao definitions to get to the correct dao name
				List queries = ((XMLConfiguration)queryConfig).configurationsAt("dao-query");
				for(Iterator it = queries.iterator(); it.hasNext();)
					{
					HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
					String cfgQueryName = sub.getString("queryName");

					if (cfgQueryName.equalsIgnoreCase(queryName))
						{
							dbQuery = sub.getString("queryString");
					
						break;
						}
					}
				
				//System.out.println(queryName+" : "+dbQuery);
				
				if (dbQuery != null && !dbQuery.equals(""))
					return dbQuery;
				else
					{
					// query is not configured in the queries.xml file
						return null;
					}
				}
			catch (Exception e)
				{
					e.printStackTrace();
					//throw new CMSException(e);
				}
			}
		else
			{
				
				// not able to load config - throw Exception
				//throw new CMSException("Query configuration not available");
			}
			
		return dbQuery;
			
			
		}
}
